/*
 * @Author: cwd
 * @Date: 2022-06-02 15:16:35
 * @LastEditors: cwd
 * @LastEditTime: 2022-06-02 15:18:07
 * @FilePath: \koa2typecsript\src\middlewares\validateParams.ts
 * @Description: 
 * 
 * Copyright (c) 2022 by cwd, All Rights Reserved. 
 */

import Joi from 'joi'
import {  Context } from 'koa'


import { parameterValidationError } from '../exception/baseException'

function genValidateParams (method: string, schema: Joi.Schema) {
  async function validateParams (ctx:Context, next: () => any) {
    let data: any
    if (method === 'get') {
      data = ctx.request.query
    } else {
      data = ctx.request.body
    }
    const { error } = schema.validate(data)
    if (error) {
       throw  new parameterValidationError(error.message)
    }
    await next()
  }
  return validateParams 
}

export default genValidateParams

